<template>
  <div id="terminal_window" />
</template>

<script>
import 'xterm/css/xterm.css';
import 'xterm/lib/xterm.js';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';

export default {
  name: 'BaseTerm',
  data() {
    return {
      // rows: '',
      term: '',
      socket: '',
      node: {
        id: 1
      }
    };
  },
  mounted() {
    // const doc = document.getElementById('terminal_window').parentElement;
    // this.rows = parseInt(doc.clientHeight / 17);
    // 连接web socket
    const url = 'ws://120.77.147.7:8082/terminal';
    // const url = 'ws://' + location.host + '/terminal';
    this.init(url);
  },
  beforeDestroy() {
    this.socket.close();
  },
  methods: {
    initXterm() {
      this.term = new Terminal({
        rendererType: 'canvas', // 渲染类型
        // rows: this.rows, // 行数
        convertEol: true, // 启用时，光标将设置为下一行的开头
        // scrollback: 10, // 终端中的回滚量
        disableStdin: false, // 是否应禁用输入
        cursorStyle: 'underline', // 光标样式
        cursorBlink: true, // 光标闪烁
        fontFamily: 'Consolas',
        theme: {
          foreground: '#6C7680', // 字体
          background: '#FAFAFA', // 背景色
          cursor: '#0A0E14', // 设置光标
          selection: '#399EE6' // 框选颜色
        }
      });
      this.$store.commit('matlab/setTerm', (str) => {
        this.term.write(str);
      });
      this.term.open(document.getElementById('terminal_window'));
      const fitAddon = new FitAddon();
      // const attachAddon = new AttachAddon();
      this.term.loadAddon(fitAddon);
      // this.term.loadAddon(attachAddon);

      // 支持输入与粘贴方法
      const _this = this; // 一定要重新定义一个this，不然this指向会出问题
      this.term.onData(function(key) {
        // let order = ["stdin",key]; //这里key值是你输入的值，数据格式一定要找后端要！！！！
        _this.socket.onsend(JSON.stringify({ type: 'command', data: key })); // 转换为字符串
      });
    },
    init(url) {
      // 实例化socket
      this.socket = new WebSocket(url);
      // 监听socket连接
      this.socket.onopen = this.open;
      // 监听socket错误信息
      this.socket.onerror = this.error;
      // 监听socket消息
      this.socket.onmessage = this.getMessage;
      // 发送socket消息
      this.socket.onsend = this.send;
    },
    open: function() {
      console.log('socket连接成功');
      this.initXterm();
      this.socket.onsend(JSON.stringify({ type: 'connect', data: this.node.id })); // 转换为字符串
      this.socket.onsend(JSON.stringify({ type: 'command', data: 'clear\r' }));
      this.socket.onsend(JSON.stringify({ type: 'command', data: 'ipython\r' }));
    },
    error: function() {
      console.log('连接错误');
    },
    close: function() {
      this.socket.close();
      console.log('socket已经关闭');
    },
    getMessage(msg) {
      console.log('msg.data: ', msg.data);
      this.term.write(msg.data);
    },
    send(order) {
      console.log(order);
      this.socket.send(order);
    }
  }
};
</script>

<style scoped>
</style>
